import cv2
import mediapipe as mp
from settings import *
import numpy as np

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands


class HandTracking:
    def __init__(self):
        self.hand_tracking = mp_hands.Hands(
            min_detection_confidence=0.5,
            min_tracking_confidence=0.5,
            max_num_hands=2  # Enable tracking for two hands
        )
        self.hands = {
            "left": {"x": 0, "y": 0, "closed": False},
            "right": {"x": 0, "y": 0, "closed": False}
        }
        self.results = None

    def scan_hands(self, image):
        rows, cols, _ = image.shape
        image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
        image.flags.writeable = False
        self.results = self.hand_tracking.process(image)
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        # Reset hand states
        self.hands["left"]["closed"] = False
        self.hands["right"]["closed"] = False

        if self.results.multi_hand_landmarks:
            for i, hand_landmarks in enumerate(self.results.multi_hand_landmarks):
                # Determine if it's left or right hand
                handedness = self.results.multi_handedness[i].classification[0].label.lower()

                # Get hand center (landmark 9 is middle finger base)
                x, y = hand_landmarks.landmark[9].x, hand_landmarks.landmark[9].y
                self.hands[handedness]["x"] = int(x * SCREEN_WIDTH)
                self.hands[handedness]["y"] = int(y * SCREEN_HEIGHT)

                # Check if hand is closed (landmark 12 is tip of middle finger)
                x1, y1 = hand_landmarks.landmark[12].x, hand_landmarks.landmark[12].y
                if y1 > y:  # If finger tip is below the base
                    self.hands[handedness]["closed"] = True

                mp_drawing.draw_landmarks(
                    image,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS,
                    mp_drawing_styles.get_default_hand_landmarks_style(),
                    mp_drawing_styles.get_default_hand_connections_style())
        return image

    def get_hand_center(self, hand="right"):
        return (self.hands[hand]["x"], self.hands[hand]["y"])

    def is_hand_closed(self, hand="right"):
        return self.hands[hand]["closed"]
    def display_hand(self):
        cv2.imshow("image", self.image)
        cv2.waitKey(1)
